package com.jiwen.controller;

import com.jiwen.dto.LoginDto;
import com.jiwen.service.LoginService;
import com.jiwen.util.SessionUtil;
import com.jiwen.vo.LoginVo;
import com.jiwen.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author shrstart
 * @create 2023-12-16-9:21
 */

@RestController
public class LoginController {

    @Autowired
    LoginService loginService;

    /*用户登陆*/
    @PostMapping("/login")
    public ResultVo login(@RequestBody LoginDto loginDto){
        LoginVo loginVo = loginService.userLogin(loginDto);

        if(loginVo != null){
            SessionUtil.put(loginVo.getToken(),loginVo);

            return ResultVo.success("登陆成功",loginVo);
        }else{
            return ResultVo.error("账号密码错误");
        }
    }

    /*用户注销*/
    @GetMapping("/logout")
    public ResultVo logout(HttpServletRequest request){

        try {
            String token = request.getHeader("token");
            SessionUtil.remove(token);

            return ResultVo.success("注销成功",null);
        }catch (Exception e){
            return ResultVo.error("注销异常");
        }
    }

}
